<?php
namespace User\Controller;

use Think\Page;
use User\Model\NiudanModel;

class NiudanController extends UserController
{
    public $project;

    public function __construct()
    {
        $this->project = "niudan";
        parent::__construct();
        if (!headers_sent() && // 如果页面头部信息还没有输出
            extension_loaded("zlib") && // 而且php已经加载了zlib扩展
            strstr($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")
        ) //而且浏览器接受GZIP
        {
            ini_set('zlib.output_compression', 'On');
            ini_set('zlib.output_compression_level', '4');
        }
    }

    public function index()
    {
        $niudan = M("redpacket");
        $where["token"] = $this->wxuser["token"];
        $where["status"] = array("NEQ", NiudanModel::STATUS_DELETE);
        $where["keyword"] = $this->project;
        $title = I("get.title", "", "");
        if (!empty($title)) {
            $where["title"] = array("LIKE", "%" . $title . "%");
            $this->assign("title", $title);
        }
        $count = $niudan->where($where)->count();
        $page = new Page($count, 15);
        $show = $page->show();

        $list = $niudan->where($where)->limit($page->firstRow . "," . $page->listRows)->order("id desc")
            ->select();
        if (!empty($list)) {
            foreach ($list as &$value) {
                if(time() > strtotime($value["enddate"])){
                    $value["status"] = NiudanModel::STATUS_STOP;
                }
                $value["link"] = "https://" . $_SERVER["SERVER_NAME"] . "/Wap/Niudan/index?id=" . $value["id"];
            }
        }
        $this->assign("page", $show);
        $this->assign("list", $list);
        $this->display();
    }

    public function statusNiudan()
    {
        $status = I("get.status", "", "");
        $condition['id'] = I("get.id", "", "");
        if ($status == "active") {
            M("redpacket")->where($condition)->save(array("status" => NiudanModel::STATUS_ACTIVE));
            $message = "发布成功";
        } elseif ($status == "apply") {
            M("redpacket")->where($condition)->save(array("status" => NiudanModel::STATUS_APPLY));
            $message = "停用成功";
        } else {
            M("redpacket")->where($condition)->save(array("status" => NiudanModel::STATUS_DELETE));
            $message = "删除成功";
        }
        $this->success($message, "", true);
    }

    public function edit()
    {
        $id = I( "get.id", -1, "" );
        $condition["id"] = $id;
        $condition["token"] = $this->wxuser["token"];
        $condition["keyword"] = $this->project;
        $niudan = M("redpacket")->where($condition)->find();
        $reserve = json_decode($niudan['reserve'], true);
        //$niudan["invite_play"] = $reserve['invite_play'];
        $niudan["address"] = $reserve["address"] ? $reserve["address"] : NiudanModel::ADDRESS_NO;
        $niudan["follow"] = $reserve["follow"] ? $reserve["follow"] : NiudanModel::FOLLOW_NO;
        $niudan["follow_qrImage"] = $reserve["follow_qrImage"] ? $reserve["follow_qrImage"] : "";

        $this->assign("id", $id);
        $this->assign("niudan", $niudan);
        $this->display();
    }

    public function update()
    {
        $id = I("post.id", -1, "");
        $data = array(
            'title' => I("post.title", "", ""),
            'keyword' => "niudan",
            'token' => $this->wxuser['token'],
            'startdate' => I("post.start_date", "", ""),
            'enddate' => I("post.end_date", "", ""),
            'info' => I("post.info", "", ""),
            'number_limits' => I("post.number_limits", -1, ""),
            'per_num_sum' => I("post.per_num_sum", "-1", ""),
            'per_num' => I("post.per_num", -1, ""),
            'createdate' => date('Y-m-d H:i:s'),
            'share_play' => I("post.share_play", 0, "")
        );

        $upload = $this->upload(2);
        $data['picurl'] = $upload[1];

        //$reserve['invite_play'] = I("post.invite_play", 0, "");
        $reserve['address'] = I("post.address", NiudanModel::ADDRESS_NO, "");
        $reserve['follow'] = I("post.follow", NiudanModel::FOLLOW_NO, "");
        if(I("post.follow", NiudanModel::FOLLOW_NO, "") == NiudanModel::FOLLOW_YES){
            $reserve['follow_qrImage'] = $upload[2];
        }else{
            $reserve['follow_qrImage'] = "";
        }
        $data['reserve'] = json_encode($reserve);

        $niudan = M("redpacket");
        $niudan_upload = M("redpacket_upload");
        if($id == -1){
            $niudan_id = $niudan->add($data);
            $niudan_upload->add(array('redpacket_id' => $niudan_id));
        }else{
            $data['id'] = $id;
            $niudan_id = $niudan->save($data);
        }
        if($niudan_id !== false){
            $this->success( "保存成功", "/User/Niudan/index");
        }else{
            $this->error( "保存失败", "/User/Niudan/index");
        }
    }

    private function upload($num)
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg', 'mp3', 'mp4', 'wav');// 设置附件上传类型
        $upload->rootPath = './Public/Uploads/niudan/'; // 设置附件上传根目录
        $upload->subName = array("date", "Ymd");
        $upload->saveName = array("uniqid", "niudan");
        $info = $upload->upload();
        if($num == 1){
            if($info['picurl1']['savename']){
                $picurl = '/Public/Uploads/niudan/' . date('Ymd') . '/' . $info['picurl1']['savename'];
            }else{
                $picurl = I("post.picurl1","","");
            }
        }else{
            for($i=1; $i<=$num; $i++){
                if($info['picurl'.$i]['savename']){
                    $picurl[$i] = '/Public/Uploads/niudan/' . date('Ymd') . '/' . $info['picurl'.$i]['savename'];
                }else{
                    $picurl[$i] = I("post.picurl".$i,"","");
                }
            }
        }
        return $picurl;
    }

    public function prize()
    {
        $update = I("post.update", false, "");
        if($update){
            $prize_num = I("post.prize_num", -1, "");
            $niudan_prize = M("redpacket_item");
            if($prize_num >= 1){
                $upload = $this->upload($prize_num);
                for($i=1; $i<=$prize_num; $i++){
                    $item_id = I("post.item_id".$i, -1, "");
                    $data = array(
                        'redpacket_id' => I("post.id", -1, ""),
                        'name' => I("post.name".$i, "", ""),
                        'level' => I("post.level".$i, "", ""),
                        'number' => I("post.number".$i, "", ""),
                        'reserve' => I("post.reserve".$i, "", ""),
                        'status' => NiudanModel::PRIZE_ACTIVE,
                        'pic' => ($prize_num == 1) ? $upload : $upload[$i]
                    );
                    if($item_id > 0){
                        $niudan_prize_id = $niudan_prize->where(['id' => $item_id])->save($data);
                    }else{
                        $niudan_prize_id = $niudan_prize->add($data);
                    }
                }
                if($niudan_prize_id !== false){
                    $this->success( "保存成功", "/User/Niudan/index");
                }else{
                    $this->error( "保存失败", "/User/Niudan/index");
                }
            }else{
                $this->error( "保存失败", "/User/Niudan/index");
            }
        }else {
            $id = I("get.id", -1, "");
            $where["redpacket_id"] = $id;
            $where["status"] = array("eq", NiudanModel::PRIZE_ACTIVE);
            $prizes = M("redpacket_item")->where($where)->select();
            $levels = NiudanModel::getLevel("all");
            $this->assign("id", $id);
            $this->assign("prizes", $prizes);
            $this->assign("levels", $levels);
            $this->display();
        }
    }

    public function deletePrize()
    {
        $where['id'] = I( "get.id", "", "" );
        $updated = M("redpacket_item")->where($where)->save( array('status'=>NiudanModel::PRIZE_DELETE));
        if($updated !== false){
            $this->success( "删除奖项成功", "", true);
        }else{
            $this->error( "删除奖项失败", "", true);
        }
    }

    public function award_list()
    {
        $id = I("get.id","","");
        $where = "award.pid=".$id." and award.zhongjiang = ".NiudanModel::ZHONGJIANG_YES.
            " and award.status!=".NiudanModel::STATUS_DELETE;
        $where .= " and fans.openid=award.openid and fans.pid=award.pid";
        $query = I("get.query", "", "");
        $prize_id = I("get.prize_id", -1, "");
        if (!empty($query)) {
            $where .= " and (fans.name like '%".$query."%' or fans.phone like '%".$query."%')";
            $this->assign("query", $query);
        }
        if($prize_id != -1){
            $where .= " and award.award_id=".$prize_id;
        }
        $count = M()->table(array('esm_redpacket_fansaward' => 'award','esm_redpacket_fans' => 'fans'))->where($where)
            ->count();
        $page = new Page($count, 15);
        $show = $page->show();
        $list = M()->table(array('esm_redpacket_fansaward' => 'award','esm_redpacket_fans' => 'fans'))
            ->field('award.id,award.award_id,award.zhongjiang,award.createdate,award.status,fans.name,fans.phone,
                fans.address')
            ->where($where)
            ->order('award.id desc')->select();
        $prize = $prizes = array();
        if(!empty($list)){
            foreach ($list as $value) {
                $prize[] = $value['award_id'];  //检查 todo
            }
            $prize = array_flip(array_flip($prize));
            $items_where['id'] = array('IN', $prize);
            $items = M('redpacket_item')->where($items_where)->select();
            foreach ($items as $item){
                $prizes[$item['id']]['award_level'] = NiudanModel::getLevel($item['level']);
                $prizes[$item['id']]['award_name'] = $item['name'];
            }
            foreach ($list as &$li){
                $li['prize_level'] = $prizes[$li['award_id']]['award_level'];
                $li['prize_name'] = $prizes[$li['award_id']]['award_name'];
                $li['address'] = $li['address'];
            }
        }
        $niudan_prize = M('redpacket_item')->where(['redpacket_id' => $id, 'status' => NiudanModel::PRIZE_ACTIVE])
            ->select();
        $niudan_prize[-1] = array('id' => -1, 'name' => "无");
        $this->assign("page", $show);
        $this->assign("list", $list);
        $this->assign("id", $id);
        $this->assign("niudan_prize", $niudan_prize);
        $this->assign("prize_id", $prize_id);
        $this->display();
    }

    public function statusAward()
    {
        $status = I("get.status", "", "");
        $condition['id'] = I("get.id", "", "");
        if ($status == "delete") {
            M("redpacket_fansaward")->where($condition)->save(array("status" => NiudanModel::AWARD_DELETE));
            $message = "删除成功";
        } else {
            M("redpacket_fansaward")->where($condition)->save(array("status" => NiudanModel::AWARD_CHECK));
            $message = "核销成功";
        }
        $this->success($message, "", true);
    }

    public function exportAwards()
    {
        set_time_limit(0);
        $id = I("get.id", "", "");
        if (empty($id)) {
            return $this->redirect("/User/Niudan/index");
        }
        vendor('phpexcel.PHPExcel');
        $objExcel = new \PHPExcel();
        $objActSheet = $objExcel->getActiveSheet();
        $objActSheet->getColumnDimension('A')->setWidth(30);
        $objActSheet->getColumnDimension('B')->setWidth(30);
        $objActSheet->getColumnDimension('C')->setWidth(30);
        $objActSheet->getColumnDimension('D')->setWidth(20);
        $objActSheet->getColumnDimension('E')->setWidth(20);
        $objActSheet->getColumnDimension('F')->setWidth(30);
        $objActSheet->getColumnDimension('G')->setWidth(30);
        $objActSheet->getColumnDimension('H')->setWidth(20);
        $objActSheet->setCellValue('A1', "姓名");
        $objActSheet->setCellValue('B1', "联系方式");
        $objActSheet->setCellValue('C1', "地址");
        $objActSheet->setCellValue('D1', "是否中奖");
        $objActSheet->setCellValue('E1', "奖项等级");
        $objActSheet->setCellValue('F1', "奖项名称");
        $objActSheet->setCellValue('G1', "参与时间");
        $objActSheet->setCellValue('H1', "奖品状态");

        $where = "award.pid=".$id." and award.zhongjiang = ".NiudanModel::ZHONGJIANG_YES.
            " and award.status!=".NiudanModel::STATUS_DELETE;
        $where .= " and fans.openid=award.openid and fans.pid=award.pid";
        $query = I("get.query", "", "");
        $prize_id = I("get.prize_id", -1, "");
        if (!empty($query)) {
            $where .= " and (fans.name like '%".$query."%' or fans.phone like '%".$query."%')";
            $this->assign("query", $query);
        }
        if($prize_id != -1){
            $where .= " and award.award_id=".$prize_id;
        }
        $list = M()->table(array('esm_redpacket_fansaward' => 'award','esm_redpacket_fans' => 'fans'))
            ->field('award.id,award.award_id,award.zhongjiang,award.createdate,award.status,fans.name,fans.phone,
                fans.address')
            ->where($where)
            ->order('award.id desc')->select();
        $prize = $prizes = array();
        if(!empty($list)){
            foreach ($list as $value) {
                $prize[] = $value['award_id'];
            }
            $prize = array_flip(array_flip($prize));
            $items_where['id'] = array('IN', $prize);
            $items = M('redpacket_item')->where($items_where)->select();
            foreach ($items as $item){
                $prizes[$item['id']]['award_level'] = NiudanModel::getLevel($item['level']);
                $prizes[$item['id']]['award_name'] = $item['name'];
            }
            foreach ($list as &$li){
                $li['prize_level'] = $prizes[$li['award_id']]['award_level'];
                $li['prize_name'] = $prizes[$li['award_id']]['award_name'];
                $li['address'] = $li['address'];
            }
        }
        $line = 2;
        if(!empty($list)){
            foreach ($list as $value) {
                $objActSheet->setCellValue('A' . $line, $value['name']);
                $objActSheet->setCellValue('B' . $line, $value['phone']);
                $objActSheet->setCellValue('C' . $line, $value['address']);
                if($value['zhongjiang'] == NiudanModel::ZHONGJIANG_NO){
                    $zhongjiang_status = "否";
                }else{
                    $zhongjiang_status = "是";
                }
                $objActSheet->setCellValue('D' . $line, $zhongjiang_status);
                $objActSheet->setCellValue('E' . $line, $value['prize_level']);
                $objActSheet->setCellValue('F' . $line, $value['prize_name']);
                $objActSheet->setCellValue('G' . $line, $value['createdate']);
                if($value['status'] == NiudanModel::AWARD_CHECK){
                    $check_status = "已核销";
                }else{
                    $check_status = "未核销";
                }
                $objActSheet->setCellValue('H' . $line, $check_status);
                $objActSheet->getRowDimension($line)->setRowHeight(20);
                $line++;
            }
        }
        $fileName = '中奖名单' . date('Ymd') . '.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = new \PHPExcel_Writer_Excel2007($objExcel);
        $objWriter->save('php://output');
    }

    public function button_setting()
    {
        $update = I("post.update", false, "");
        if($update){
            $upload_id = I("post.upload_id", -1, "");
            $upload = $this->upload(4);
            $niudan_upload = M("redpacket_upload");
            $data = array(
                'id' => $upload_id,
                'image1' => $upload[1],                    //分享按钮
                'image2' => $upload[2],                    //再玩一次按钮
                'bgm' => I("post.custom_type", 0, "")      //自定义按钮类型
            );
            if(I("post.custom_type", 0, "") == 0){
                $data['image3'] = "";                       //自定义按钮图片
                $data['audio1'] = "";                       //自定义按钮外链
                $data['audio2'] = "";                       //微信公号图片
            }elseif(I("post.custom_type", 0, "") == 1){
                $data['image3'] = $upload[3];
                $data['audio1'] = I("post.custom_link", "", "");
                $data['audio2'] = "";
            }else{
                $data['image3'] = "";
                $data['audio1'] = "";
                $data['audio2'] = $upload[4];
            }
            $niudan_upload_id = $niudan_upload->save($data);
            if($niudan_upload_id !== false){
                $this->success( "保存成功", "/User/Niudan/index");
            }else{
                $this->error( "保存失败", "/User/Niudan/index");
            }
        }else{
            $id = I( "get.id", -1, "" );
            $upload = M("redpacket_upload")->where(['redpacket_id' => $id])->find();
            if(!empty($upload)){
                $niudan = array(
                    'upload_id' => $upload['id'],
                    'button_share' => $upload['image1'],  //分享按钮
                    'button_again' => $upload['image2'],  //再玩一次按钮
                    'custom_type' => $upload['bgm'],      //自定义按钮类型
                    'custom_image' => $upload['image3'],  //自定义按钮图片
                    'custom_link' => $upload['audio1'],   //自定义按钮外链
                    'weixin_image' => $upload['audio2'],  //微信公号图片
                );
            }
            $this->assign("id", $id);
            $this->assign("niudan", $niudan);
            $this->display();
        }
    }

    public function share_setting()
    {
        $update = I("post.update", false, "");
        if($update){
            $data = array(
                'id' => I("post.id", -1, ""),
                'share_title' => I("post.share_title", "", ""),
                'share_desc' => I("post.share_desc", "", ""),
                'share_link' => I("post.share_link", "", "")
            );
            $data['share_img'] = $this->upload(1);
            $niudan = M("redpacket");
            $niudan_id = $niudan->save($data);
            if($niudan_id !== false){
                $this->success( "保存成功", "/User/Niudan/index");
            }else{
                $this->error( "保存失败", "/User/Niudan/index");
            }
        }else {
            $id = I( "get.id", -1, "" );
            $condition["id"] = $id;
            $condition["token"] = $this->wxuser["token"];
            $niudan = M("redpacket")->where($condition)->find();
            $this->assign("id", $id);
            $this->assign("niudan", $niudan);
            $this->display();
        }
    }

    public function statistics(){
        $id = I("get.id", -1, "");
        $where['pid'] = $id;
        $where['status'] = array("NEQ", NiudanModel::AWARD_DELETE);

        $list = M("redpacket_fansaward")->where($where)->order('id desc')->select();
        $all_date = array();
        if(!empty($list)) {
            foreach ($list as $value) {
                $create_date = date("Y-m-d", strtotime($value["createdate"]));
                if (!in_array($create_date, $all_date)) {
                    array_push($all_date, $create_date);
                    $new_list[] = array("date" => $create_date);
                }
                $where_share["url"] = "https://" . $_SERVER['HTTP_HOST'] . "/Wap/Niudan/index?id=" . $id;
                $share_list = M("wechat_share")->where($where_share)->order('shareId desc')->select();
                foreach ($new_list as &$new_value){
                    $pv = $uv = $wx_share = 0;
                    $all_openid = array();
                    foreach ($list as $pv_value){
                        $pv_date = date("Y-m-d", strtotime($pv_value["createdate"]));
                        if($new_value["date"] == $pv_date){
                            $pv++;
                            $new_value["pv"] = $pv;                     //PV
                            if(!in_array($pv_value["openid"], $all_openid)){
                                array_push($all_openid, $pv_value["openid"]);
                                $uv++;
                                $new_value["uv"] = $uv;                 //UV
                            }
                        }
                    }
                    $new_value["wx_share"] = 0;
                    if(!empty($share_list)){
                        foreach ($share_list as $share_value){
                            $share_date = date("Y-m-d", strtotime($share_value["createdate"]));
                            if($new_value["date"] == $share_date){
                                $wx_share++;
                                $new_value["wx_share"] = $wx_share;     //转发量
                            }
                        }
                    }
                }
            }
        }
        $count = count($new_list);
        if(!empty($new_list)){
            $new_list = array_reverse($new_list);
            foreach ($new_list as &$new){
                $new['date']  = date("m-d", strtotime($new['date']));
            }
            $new_list = json_encode($new_list);
        }
        $this->assign("id", $id);
        $this->assign("count", $count);
        $this->assign("list", $new_list);
        $this->display("statistics_graph");
    }

    public function statistics_date(){
        $id = I("get.id", -1, "");
        $where['pid'] = $id;
        $where['status'] = array("NEQ", NiudanModel::AWARD_DELETE);

        $list = M("redpacket_fansaward")->where($where)->order('id desc')->select();
        $all_date = $new_list = array();
        if(!empty($list)){
            foreach ($list as $value){
                $create_date = date("Y-m-d", strtotime($value["createdate"]));
                if(!in_array($create_date, $all_date)){
                    array_push($all_date, $create_date);
                    $new_list[] = array("date" => $create_date);
                }
            }
            $where_share["url"] = "https://" . $_SERVER['HTTP_HOST'] . "/Wap/Niudan/index?id=" . $id;
            $share_list = M("wechat_share")->where($where_share)->order('shareId desc')->select();
            foreach ($new_list as &$new_value){
                $pv = $uv = $wx_share = 0;
                $all_openid = array();
                foreach ($list as $pv_value){
                    $pv_date = date("Y-m-d", strtotime($pv_value["createdate"]));
                    if($new_value["date"] == $pv_date){
                        $pv++;
                        $new_value["pv"] = $pv;                     //PV
                        if(!in_array($pv_value["openid"], $all_openid)){
                            array_push($all_openid, $pv_value["openid"]);
                            $uv++;
                            $new_value["uv"] = $uv;                 //UV
                        }
                    }
                }
                $new_value["wx_share"] = 0;
                if(!empty($share_list)){
                    foreach ($share_list as $share_value){
                        $share_date = date("Y-m-d", strtotime($share_value["createdate"]));
                        if($new_value["date"] == $share_date){
                            $wx_share++;
                            $new_value["wx_share"] = $wx_share;     //转发量
                        }
                    }
                }
            }
        }
        $this->assign("id", $id);
        $this->assign("list", $new_list);
        $this->display("statistics_date");
    }

    public function deleteDates()
    {
        $id = I("get.id", -1, "");
        $dates = I("get.dates", "", "");
        if(!empty($dates)){
            $dates = explode('|', $dates);
        }
        $where['pid'] = $id;
        $where['status'] = array("NEQ", NiudanModel::AWARD_DELETE);
        $list = M("redpacket_fansaward")->where($where)->order('id desc')->select();
        $updated = false;
        if(!empty($list)){
            foreach ($list as $value){
                $create_date = date("Y-m-d", strtotime($value["createdate"]));
                foreach ($dates as $date){
                    if($date != "" && $create_date == $date){
                        $updated = M("redpacket_fansaward")->where(["id" => $value["id"]])
                            ->save(array("status" => NiudanModel::AWARD_DELETE));
                    }
                }
            }
        }
        if($updated !== false){
            $this->success( "删除成功", "", true);
        }else{
            $this->error( "删除失败", "", true);
        }
    }

    public function deleteDate()
    {
        $id = I("get.id", -1, "");
        $date = I("get.date", "", "");
        $where['pid'] = $id;
        $where['status'] = array("NEQ", NiudanModel::AWARD_DELETE);
        $list = M("redpacket_fansaward")->where($where)->order('id desc')->select();
        $updated = false;
        if(!empty($list)){
            foreach ($list as $value){
                $create_date = date("Y-m-d", strtotime($value["createdate"]));
                if($date != "" && $create_date == $date){
                    $updated = M("redpacket_fansaward")->where(["id" => $value["id"]])
                        ->save(array("status" => NiudanModel::AWARD_DELETE));
                }
            }
        }
        if($updated !== false){
            $this->success( "删除成功", "", true);
        }else{
            $this->error( "删除失败", "", true);
        }
    }

    public function exportDate()
    {
        set_time_limit(0);
        $id = I("get.id", "", "");
        if (empty($id)) {
            $this->redirect("/User/Niudan/index");
        }
        vendor('phpexcel.PHPExcel');
        $objExcel = new \PHPExcel();
        $objActSheet = $objExcel->getActiveSheet();
        $objActSheet->getColumnDimension('A')->setWidth(30);
        $objActSheet->getColumnDimension('B')->setWidth(30);
        $objActSheet->getColumnDimension('C')->setWidth(30);
        $objActSheet->getColumnDimension('D')->setWidth(30);
        $objActSheet->setCellValue('A1', "时间");
        $objActSheet->setCellValue('B1', "PV");
        $objActSheet->setCellValue('C1', "UV");
        $objActSheet->setCellValue('D1', "转发量");
        $line = 2;
        $where['pid'] = $id;
        $where['status'] = array("NEQ", NiudanModel::AWARD_DELETE);
        $list = M("redpacket_fansaward")->where($where)->order('id desc')->select();
        $all_date = $new_list = array();
        if(!empty($list)){
            foreach ($list as $value){
                $create_date = date("Y-m-d", strtotime($value["createdate"]));
                if(!in_array($create_date, $all_date)){
                    array_push($all_date, $create_date);
                    $new_list[] = array("date" => $create_date);
                }
            }
            $where_share["url"] = "https://" . $_SERVER['HTTP_HOST'] . "/Wap/Niudan/index?id=" . $id;
            $share_list = M("wechat_share")->where($where_share)->order('shareId desc')->select();
            foreach ($new_list as &$new_value){
                $pv = $uv = $wx_share = 0;
                $all_openid = array();
                foreach ($list as $pv_value){
                    $pv_date = date("Y-m-d", strtotime($pv_value["createdate"]));
                    if($new_value["date"] == $pv_date){
                        $pv++;
                        $new_value["pv"] = $pv;                     //PV
                        if(!in_array($pv_value["openid"], $all_openid)){
                            array_push($all_openid, $pv_value["openid"]);
                            $uv++;
                            $new_value["uv"] = $uv;                 //UV
                        }
                    }
                }
                $new_value["wx_share"] = 0;
                if(!empty($share_list)){
                    foreach ($share_list as $share_value){
                        $share_date = date("Y-m-d", strtotime($share_value["createdate"]));
                        if($new_value["date"] == $share_date){
                            $wx_share++;
                            $new_value["wx_share"] = $wx_share;     //转发量
                        }
                    }
                }
            }
        }
        if(!empty($new_list)){
            foreach ($new_list as $new) {
                $objActSheet->setCellValue('A' . $line, $new['date']);
                $objActSheet->setCellValue('B' . $line, $new['pv']);
                $objActSheet->setCellValue('C' . $line, $new['uv']);
                $objActSheet->setCellValue('D' . $line, $new['wx_share']);
                $objActSheet->getRowDimension($line)->setRowHeight(20);
                $line++;
            }
        }
        $fileName = '最新数据' . date('Ymd') . '.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = new \PHPExcel_Writer_Excel2007($objExcel);
        $objWriter->save('php://output');
    }

    public function statistics_user(){
        $id = I("get.id", -1, "");
        $where['pid'] = $id;
        $where['status'] = array("NEQ", NiudanModel::AWARD_DELETE);
        $count = M("redpacket_fansaward")->where($where)->count();

        $page = new Page($count, 15);
        $show = $page->show();
        $this->assign("page", $show);

        $list = M("redpacket_fansaward")->where($where)->limit($page->firstRow . ',' . $page->listRows)
            ->order('id desc')->select();
        if(!empty($list)){
            foreach ($list as &$value){
                $reserve = json_decode($value["reserve"], true);
                $value["area"] = $reserve["area"];
                $value["phoneType"] = $reserve["phoneType"];
                $value["origin"] = $reserve["origin"];
            }
        }
        $this->assign("id", $id);
        $this->assign("list", $list);
        $this->display("statistics_user");
    }

    public function deleteUsers()
    {
        $ids = I( "get.ids", "", "" );
        if(!empty($ids)){
            $ids = explode('|', $ids);
        }
        $where['id'] = array('IN', $ids);
        $updated = M("redpacket_fansaward")->where($where)->save(array('status' => NiudanModel::AWARD_DELETE));
        if($updated !== false){
            $this->success("删除成功", "", true);
        }else{
            $this->error("删除失败", "", true);
        }
    }

    public function deleteUser()
    {
        $where['id'] = I("get.id", -1, "");
        $updated = M("redpacket_fansaward")->where($where)->save(array('status' => NiudanModel::AWARD_DELETE));
        if($updated !== false){
            $this->success("删除成功", "", true);
        }else{
            $this->error("删除失败", "", true);
        }
    }

    public function exportUser()
    {
        set_time_limit(0);
        $id = I("get.id", "", "");
        if (empty($id)) {
            $this->redirect("/User/Niudan/index");
        }
        vendor('phpexcel.PHPExcel');
        $objExcel = new \PHPExcel();
        $objActSheet = $objExcel->getActiveSheet();
        $objActSheet->getColumnDimension('A')->setWidth(10);
        $objActSheet->getColumnDimension('B')->setWidth(30);
        $objActSheet->getColumnDimension('C')->setWidth(30);
        $objActSheet->getColumnDimension('D')->setWidth(30);
        $objActSheet->getColumnDimension('E')->setWidth(30);
        $objActSheet->setCellValue('A1', "编号");
        $objActSheet->setCellValue('B1', "用户");
        $objActSheet->setCellValue('C1', "地区");
        $objActSheet->setCellValue('D1', "来源");
        $objActSheet->setCellValue('E1', "手机型号");
        $objActSheet->setCellValue('F1', "时间");
        $where['pid'] = $id;
        $where['status'] = array("NEQ", NiudanModel::AWARD_DELETE);
        $list = M("redpacket_fansaward")->where($where)->order('id desc')->select();
        $line = 2;
        if(!empty($list)){
            foreach ($list as $value) {
                $reserve = json_decode($value["reserve"], true);
                $area = $reserve["area"];
                $phoneType = $reserve["phoneType"];
                $origin = $reserve["origin"];
                $objActSheet->setCellValue('A' . $line, $value['id']);
                $objActSheet->setCellValue('B' . $line, $value['openid']);
                $objActSheet->setCellValue('C' . $line, $area);
                $objActSheet->setCellValue('D' . $line, $origin);
                $objActSheet->setCellValue('E' . $line, $phoneType);
                $objActSheet->setCellValue('F' . $line, $value['createdate']);
                $objActSheet->getRowDimension($line)->setRowHeight(20);
                $line++;
            }
        }
        $fileName = '用户行为' . date('Ymd') . '.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = new \PHPExcel_Writer_Excel2007($objExcel);
        $objWriter->save('php://output');
    }
}